<?php
/**
 * 
 * @author yusaint
 * @since 2014-3-9
 * @project Pfinal
 */
class Pfinal_Route_Default extends Pfinal_Route_Abstract implements Pfinal_Route_Interface_Base {
	/*
	 * 解析url，按照深度优先查找
	 * a/b/c/p1-p2-p3
	 * www.baidu.com/index.php
	 * pathinfo为空的时候，返回 index/index
	 * www.baidu.com/index.php/a=>www.baidu.com/index.php/a/index
	 * pathinfo不为空的时候，返回a controllerKey=a actionKey='index'
	 * www.baidu.com/index.php/a/b/c => (a/b/c) =>(a/b, c)
	 * controllerKey =a/b actionKey = c
	 * www.baidu.com/index.php/a/b/c/d/e/p1-p2-p3 => (a/b/c/d/e) =>(a/b, c/d/e)
	 */
	public function route($url,PfinalConfig $kernelConfig) {
		// TODO Auto-generated method stub
		$segments = explode('/', $url);
		//按照深度优先规则搜索controller的文件
		$path = CONTROLLER;
		foreach ($segments as $k=>$segment){	
			$this->controllerKey .= $segment;
			$instance = $this->isController($path, $segment);
			if (!is_null($instance)){
				$this->controllerInstance = $instance;
				break;
			}
			
			$path .= $segment.DIRECTORY_SEPARATOR;
		}
		if (is_null($this->controllerInstance)){
			throw new Pfinal_Exception_Runtime("can not find the controller");
		}
		//case1 www.baidu.com/demo/b controllerKey = demo  
		$pos = strpos($url,$this->controllerKey);
		$url = substr($url, $pos+strlen($this->controllerKey));
		$url = trim($url,'/');
		if (empty($url)){
			$this->actionKey = 'index';
			$this->parameters = array();
		}else{
			$pos = strstr($url, '/');
			if ($pos===false){
				$this->actionKey = strtolower($url);
				$this->parameters = array();
			}else{
				//a/b这种形式
				$segments = explode('/',$url);
				$nSegments = count($segments);
				$this->actionKey = reset($segments);//第一个元素作为actionKey
				$this->parameters = explode($kernelConfig->getConstant()->getUrlSeparator(),end($segments));//最后一个元素作为parameters
			}
		}		
	}
}
?>